package com.css.zfzx.sjcj.modules.qhsitushearwave.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.css.zfzx.sjcj.common.utils.BeanUtil;
import com.css.zfzx.sjcj.common.utils.EasyPoiExcelUtil;
import com.css.zfzx.sjcj.common.utils.ServerUtil;
import com.css.zfzx.sjcj.modules.qhdrilloverview.repository.QhDrillOverviewRepository;
import com.css.zfzx.sjcj.modules.qhdrilloverview.repository.entity.QhDrillOverviewEntity;
import com.css.zfzx.sjcj.modules.qhsitushearwave.repository.QhSituShearWaveNativeRepository;
import com.css.zfzx.sjcj.modules.qhsitushearwave.repository.QhSituShearWaveRepository;
import com.css.zfzx.sjcj.modules.qhsitushearwave.repository.entity.QhSituShearWaveEntity;
import com.css.zfzx.sjcj.modules.qhsitushearwave.service.QhSituShearWaveService;
import com.css.zfzx.sjcj.modules.qhsitushearwave.viewobjects.QhSituShearWaveQueryParams;
import com.css.zfzx.sjcj.modules.qhsitushearwave.viewobjects.QhSituShearWaveVO;
import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.sys.dict.repository.entity.DictItemEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.PageImpl;
import com.css.bpm.platform.utils.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @author aa
 * @date 2020-11-12
 */
@Slf4j
@Service
public class QhSituShearWaveServiceImpl implements QhSituShearWaveService {

	@Autowired
    private QhSituShearWaveRepository qhSituShearWaveRepository;
    @Autowired
    private QhSituShearWaveNativeRepository qhSituShearWaveNativeRepository;
    @Autowired
    private QhDrillOverviewRepository qhDrillOverviewRepository;

    @Override
    public JSONObject queryQhSituShearWaves(QhSituShearWaveQueryParams queryParams, int curPage, int pageSize) {
        Page<QhSituShearWaveEntity> qhSituShearWavePage = this.qhSituShearWaveNativeRepository.queryQhSituShearWaves(queryParams, curPage, pageSize);
        JSONObject jsonObject = PlatformPageUtils.formatPageData(qhSituShearWavePage);
        return jsonObject;
    }


    @Override
    public QhSituShearWaveEntity getQhSituShearWave(String id) {
        QhSituShearWaveEntity qhSituShearWave = this.qhSituShearWaveRepository.findById(id).orElse(null);
         return qhSituShearWave;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public QhSituShearWaveEntity saveQhSituShearWave(QhSituShearWaveEntity qhSituShearWave) {
        String uuid = UUIDGenerator.getUUID();
        qhSituShearWave.setId(uuid);
        qhSituShearWave.setCreateUser(PlatformSessionUtils.getUserId());
        qhSituShearWave.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
        qhSituShearWave.setIsValid("1");
        qhSituShearWave.setReviewStatus("0");
        qhSituShearWave.setQualityinspectionStatus("0");
        this.qhSituShearWaveRepository.save(qhSituShearWave);
        return qhSituShearWave;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public QhSituShearWaveEntity updateQhSituShearWave(QhSituShearWaveEntity qhSituShearWave) {
        qhSituShearWave.setUpdateUser(PlatformSessionUtils.getUserId());
        qhSituShearWave.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        this.qhSituShearWaveRepository.save(qhSituShearWave);
        return qhSituShearWave;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteQhSituShearWaves(List<String> ids) {
        List<QhSituShearWaveEntity> qhSituShearWaveList = this.qhSituShearWaveRepository.findAllById(ids);
        if(!PlatformObjectUtils.isEmpty(qhSituShearWaveList) && qhSituShearWaveList.size() > 0) {
            for(QhSituShearWaveEntity qhSituShearWave : qhSituShearWaveList) {
                this.qhSituShearWaveRepository.delete(qhSituShearWave);
            }
        }
    }

    @Override
    public List<DictItemEntity> getValidDictItemsByDictCode(String dictCode) {
        List<DictItemEntity> validDictItems = PlatformAPI.getDictAPI().getValidDictItemsByDictCode(dictCode);
        return validDictItems;
    }

    @Override
    public String findByDictCodeAndDictItemCode(String dictCode, String dictItemCode){
        DictItemEntity dictItem = PlatformAPI.getDictAPI().getValidDictItemByDictCodeAndDictItemCode(dictCode, dictItemCode);
        String dictItemName = "";
        if(PlatformObjectUtils.isNotEmpty(dictItem)){
            dictItemName = dictItem.getDictItemName();
        }
        return dictItemName;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void submitQhSituShearWaves(String ids) {
        List<String> idList = Arrays.asList(ids.split(","));
        List<QhSituShearWaveEntity> qhDrillOverviewList = this.qhSituShearWaveRepository.findAllById(idList);
        if(!PlatformObjectUtils.isEmpty(qhDrillOverviewList) && qhDrillOverviewList.size() > 0) {
            for(QhSituShearWaveEntity qhDrillOverview : qhDrillOverviewList) {
                qhDrillOverview.setUpdateUser(PlatformSessionUtils.getUserId());
                qhDrillOverview.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                qhDrillOverview.setReviewStatus("1");
                this.qhSituShearWaveRepository.save(qhDrillOverview);
            }
        }
    }

    @Override
    public String importExcel(MultipartFile file) {
        try {
            // 返回的消息
            StringBuilder returnMsg = new StringBuilder();
            // 导入的参数信息
            ImportParams params = new ImportParams();
            // 设置简析的第一行
            params.setHeadRows(1);
            params.setTitleRows(1);
            // 是否需要校验
            params.setNeedVerify(true);
            // 获取到Excel数据
            ExcelImportResult<QhSituShearWaveVO> result = ExcelImportUtil.importExcelMore(file.getInputStream(), QhSituShearWaveVO.class, params);
            List<QhSituShearWaveVO> list = result.getList();
            // 批量新增
            this.saveExcel(list);
            returnMsg.append("成功导入" + result.getList().size() + "条，失败" + result.getFailList().size() + "条<br/>");
            if (result.isVerifyFail()) {
                // 校验返回失败行信息
                Iterator<QhSituShearWaveVO> iterator = result.getFailList().iterator();
                while (iterator.hasNext()) {
                    QhSituShearWaveVO areaVO = iterator.next();
                    String error = "";
                    returnMsg.append("第" + areaVO.getRowNum() + "行" + areaVO.getErrorMsg() + "<br/>");
                    returnMsg.append(error);
                }
            }
            return returnMsg.toString();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return "导入失败，请检查数据正确性";
        }
    }

    @Override
    public String exportExcel(String ids, HttpServletResponse response) {
        List<String> idList = Arrays.asList(ids.split(","));
        List<QhSituShearWaveEntity> areaEntities = qhSituShearWaveRepository.findAllById(idList);

        return exportExcel(areaEntities,response);
    }

    @Override
    public String exportExcel(List<QhSituShearWaveEntity> areaEntities, HttpServletResponse response) {
        try {
            // 深拷贝
            ArrayList<QhSituShearWaveVO> vos = new ArrayList<>();
            for (QhSituShearWaveEntity areaEntity : areaEntities) {
                QhSituShearWaveVO vo = new QhSituShearWaveVO();
                BeanUtils.copyProperties(areaEntity, vo);
                vos.add(vo);
            }
            // 导出
            EasyPoiExcelUtil.exportExcel(vos, "钻孔原位剪切波速测试结果统计", "钻孔原位剪切波速测试结果", QhSituShearWaveVO.class, "钻孔原位剪切波速测试结果.xls", response);
            return "导出成功";
        } catch (Exception e) {
            e.printStackTrace();
            return e.getMessage();
        }
    }

    private void saveExcel(List<QhSituShearWaveVO> list) {
        for (int i = 0; i < list.size(); i++) {
//            QhSituShearWaveEntity areaEntity = new QhSituShearWaveEntity();
            QhSituShearWaveVO areaVO = list.get(i);
            QhSituShearWaveEntity areaEntity = qhSituShearWaveRepository.findById(areaVO.getId()).get();
            // 将VO数据映射拷贝到库表中
            BeanUtil.copyPropertiesIgnoreNull(areaVO, areaEntity);
            updateQhSituShearWave(areaEntity);
        }
    }

    private void setCheckFields(Map<String,String> fields){
        fields.put("projectName","勘察工程名称");
        fields.put("drillCode","钻孔编号");
        fields.put("serialNumber","序号");
        fields.put("testDepth","测试深度");
        fields.put("measuredValue","实测值");
        fields.put("province","省");
        fields.put("city","市");
        fields.put("area","区/县");
    }

    @Override
    public JSONObject dataQualityCheck(List<QhSituShearWaveEntity> qhSituShearWaveList){
        JSONObject res = new JSONObject();

        try {
            if(PlatformObjectUtils.isEmpty(qhSituShearWaveList) || qhSituShearWaveList.size() < 1) {
                return res;
            }

            Map<String,JSONObject> testDepthMap = new HashMap<>();
            String depthStr = "depth";
            String entityStr = "entity";
            int index = 0;
            for(QhSituShearWaveEntity qhSituShearWave : qhSituShearWaveList){
                //检查字段值不为空
                StringBuilder errorMsg = new StringBuilder();
                Map<String, String> methods = new HashMap<>();
                setCheckFields(methods);

                ServerUtil.checkFieldNull(qhSituShearWave, methods, errorMsg);

                //测试深度
                /*float testDepth = Float.parseFloat(qhSituShearWave.getTestDepth());*/
                double testDepth =Double.parseDouble(qhSituShearWave.getTestDepth());
                if(testDepth > 1000){
                    ServerUtil.addErrorMsg(errorMsg,"测试深度","深度不会超过1000");
                }

                //实测值
                float measuredValue = Float.parseFloat(qhSituShearWave.getMeasuredValue());
                if(measuredValue > 5000){
                    ServerUtil.addErrorMsg(errorMsg,"实测值","不会超过5000");
                }

                //写入系统质检原因
                String strErrorMsg = errorMsg.toString();
                if(!strErrorMsg.isEmpty()) {
                    qhSituShearWave.setQualityinspectionComments(strErrorMsg);
                    qhSituShearWave.setQualityinspectionStatus("1");
                    qhSituShearWave.setQualityinspectionResult("0");
                    this.updateQhSituShearWave(qhSituShearWave);

                    res.put(qhSituShearWave.getId(),strErrorMsg);
                } else {
                    qhSituShearWave.setQualityinspectionComments("");
                    qhSituShearWave.setQualityinspectionStatus("1");
                    qhSituShearWave.setQualityinspectionResult("1");
                    this.updateQhSituShearWave(qhSituShearWave);
                }

                //测试深度记录
                String drillCode = qhSituShearWave.getDrillCode();
                if(testDepthMap.containsKey(drillCode)){
                    JSONObject obj = testDepthMap.get(drillCode);
                    if(testDepth - obj.getFloat(depthStr) > 0.001){
                        obj.put(depthStr,testDepth);
                        obj.put(entityStr,index);
                    }
                } else {
                    JSONObject obj = new JSONObject();
                    obj.put(depthStr,testDepth);
                    obj.put(entityStr,index);
                    testDepthMap.put(drillCode,obj);
                }

                ++index;
            }

            for(Map.Entry<String,JSONObject> entry : testDepthMap.entrySet()){
                String drillCode = entry.getKey();
                JSONObject obj = entry.getValue();
                /*float testDepth = obj.getFloat(depthStr);*/
                Double testDepth = obj.getDoubleValue(depthStr);
                int entityIndex = obj.getInteger(entityStr);

                List<QhDrillOverviewEntity> qhDrillOverviewEntityList = this.qhDrillOverviewRepository.findByIsValidAndDrillCode("1",drillCode);
                if(qhDrillOverviewEntityList.size() == 1){
                    QhDrillOverviewEntity qhDrillOverviewEntity = qhDrillOverviewEntityList.get(0);
                    /*float drillDepth = Float.parseFloat(qhDrillOverviewEntity.getDrillDepth());*/
                    double drillDepth =Double.parseDouble(qhDrillOverviewEntity.getDrillDepth());
                    QhSituShearWaveEntity qhSituShearWaveEntity = qhSituShearWaveList.get(entityIndex);
                    /*if(testDepth - drillDepth > 0.0001 || testDepth - drillDepth < 0.0001){*/
                    if(testDepth!=drillDepth){
                        StringBuilder builder = new StringBuilder();
                        ServerUtil.addErrorMsg(builder,"测试深度","最后一行测试深度与终孔深度应当一致");
                        String tempStr = res.getString(qhSituShearWaveEntity.getId());
                        tempStr = tempStr == null ? "" : tempStr;
                        tempStr += builder.toString();

                        qhSituShearWaveEntity.setQualityinspectionComments(tempStr);
                        qhSituShearWaveEntity.setQualityinspectionStatus("1");
                        qhSituShearWaveEntity.setQualityinspectionResult("0");
                        this.updateQhSituShearWave(qhSituShearWaveEntity);

                        res.put(qhSituShearWaveEntity.getId(),tempStr);
                    }else {
                        qhSituShearWaveEntity.setQualityinspectionComments("");
                        qhSituShearWaveEntity.setQualityinspectionStatus("1");
                        qhSituShearWaveEntity.setQualityinspectionResult("1");
                        this.updateQhSituShearWave(qhSituShearWaveEntity);
                    }
                }
            }
        }catch (Exception e){
            log.error(e.getMessage());
        }

        return res;
    }

    @Override
    public JSONObject dataQualityCheck(String drillCodes){
        List<String> idList = Arrays.asList(drillCodes.split(","));
        List<QhSituShearWaveEntity> qhSituShearWaveList = this.qhSituShearWaveRepository.findByIsValidAndDrillCodeInOrderByCreateTimeDesc("1",idList);

        return dataQualityCheck(qhSituShearWaveList);
    }

    @Override
    public QhSituShearWaveEntity inspectionPassed(QhSituShearWaveEntity qhSituShearWave) {
        qhSituShearWave.setQualityinspectionStatus("2");
        qhSituShearWave.setQualityinspectionResult("1");
        return this.updateQhSituShearWave(qhSituShearWave);
    }

    @Override
    public QhSituShearWaveEntity inspectionFailed(QhSituShearWaveEntity qhSituShearWave) {
        qhSituShearWave.setQualityinspectionStatus("2");
        qhSituShearWave.setQualityinspectionResult("0");
        return this.updateQhSituShearWave(qhSituShearWave);
    }
}
